import { ref } from 'vue'

const todayKey = () => {
  const d = new Date()
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}${m}${day}`
}

const storage = () => (localStorage.getItem('userToken') ? localStorage : sessionStorage)

const k = (id: string) => `gc:daily:${id}:${todayKey()}`

const read = (id: string) => {
  const v = storage().getItem(k(id))
  const n = v ? parseInt(v) : 0
  return isNaN(n) ? 0 : n
}

const write = (id: string, n: number) => {
  storage().setItem(k(id), String(Math.max(0, n)))
}

export const useDailyLimits = () => {
  const touched = ref<string>('')

  const remainingOf = (id: string, limit: number) => {
    const used = read(id)
    return Math.max(0, limit - used)
  }

  const canHit = (id: string, limit: number) => remainingOf(id, limit) > 0

  const hit = (id: string) => {
    const used = read(id)
    write(id, used + 1)
    touched.value = id
  }

  const reset = (id: string) => write(id, 0)

  return { canHit, remainingOf, hit, reset, touched }
}

